import mongoose from 'mongoose'

const connectDB = async () => {
    try {
        const mongoUri = process.env.MONGODB_URI || 'mongodb://localhost:27017/webapp_db'
        const conn = await mongoose.connect(mongoUri, {
            useNewUrlParser: true,
            useUnifiedTopology: true
        })

        console.log(`✅ MongoDB 连接成功: ${conn.connection.host}`)

        // 监听数据库连接事件
        mongoose.connection.on('error', err => {
            console.error('❌ MongoDB 连接错误:', err)
        })

        mongoose.connection.on('disconnected', () => {
            console.log('⚠️  MongoDB 连接断开')
        })

    } catch (error) {
        console.error('❌ MongoDB 连接失败:', error.message)
        process.exit(1)
    }
}

export default connectDB
